package com.squareup.picasso;

import android.net.Uri;
import android.util.Pair;

import com.bytedance.retrofit2.ResponseWrapper;
import com.bytedance.retrofit2.mime.TypedInput;
import com.bytedance.ttnet.INetworkApi;
import com.bytedance.ttnet.b.RequestParams;
import com.bytedance.ttnet.utils.RetrofitUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;

import inline.NetworkDemo;

public final class Downloader {
    public static class ResponseException extends IOException {
        final boolean localCacheOnly;
        final int responseCode;

        public ResponseException(String message, int networkPolicy, int responseCode) {
            super(message);
            this.localCacheOnly = NetworkPolicy.isOfflineOnly(networkPolicy);
            this.responseCode = responseCode;
        }
    }

    public static final class Response {
        final InputStream stream;
        final long length;

        public Response(InputStream stream, long length) {
            if (stream == null) {
                throw new IllegalArgumentException("Stream may not be null.");
            }
            this.stream = stream;
            this.length = length;
        }
    }

    public Downloader() {

    }

    public static Response load(Uri uri, int networkPolicy) throws IOException {
        String url = uri.toString();
        try {
            LinkedHashMap queryMap = new LinkedHashMap();
            Pair<String, String> pair = NetworkDemo.parseUrl(url, queryMap);
            ResponseWrapper<TypedInput> response = RetrofitUtils.createService(pair.first, INetworkApi.class)
                    .downloadFile(false, -1, pair.second, queryMap, null, new RequestParams())
                    .execute();
            int status = response.rawResponse.status;
            if (status >= 300) {
                android.support.design.a.closeQuietly(response.body.in(), (String) null);
                throw new ResponseException(status + " " + response.toString(), networkPolicy, status);
            }
            return new Response(response.body.in(), response.body.length());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new IOException(throwable.getCause());
        }
    }
}

